# -*- coding:utf-8 -*-
# ouyang kui
import json
import os
import random
import uuid
import requests
import unittest

from nose.tools import assert_equal, assert_true, assert_false,assert_in
from parameterized import parameterized
from nose.plugins.attrib import attr

from utils.jktest import get_unmatch_list

# import socks
# import socket

# 如果在办公室运行，且没有设置uat环境代理，那么可以使用socks代理访问uat内网ip
# socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "10.20.3.10", 7075)
# socket.socket = socks.socksocket

# 接口文档地址http://wiki.it.yzs.io:8090/pages/viewpage.action?pageId=38921708
class TestdpsManage():

    #读取测试数据到testData
    jsonFilePath = os.path.join(os.getcwd(), "api_test_data", "unios-dps-manager-api.json")
    testData = json.load(open(jsonFilePath))

    def __init__(self):
        self.header = {'Content-Type': 'application/json'}
        self.dpsManageIP_uat = "http://172.18.10.82:8080/unios-dps-manager"  # UAT
        self.appKey_uat = "x4b2mznbegs5ksp6xz4jfmvkgoq3xug67t5m2cyx"  # UAT
        self.dpsManageIP_product = "http://172.20.6.145:8080/unios-dps-manager"  # Product
        self.appKey_product = "vbgg56jy5fuukkevsonmrevc6tag42ey2abqokq5"  # Product

        #实际使用的地址和数据
        self.usedIP = self.dpsManageIP_uat
        self.appKey = self.appKey_uat

        # 提前注册两个账号，供接口查询测试使用
        self.user1Info = self.addEnterpriseUser(getUserInfo=True)
        self.user2Info = self.addEnterpriseUser(getUserInfo=True)
        # print self.user1Info
        # print self.user2Info
        # UAT test info
        # self.user1Info = {'userName': 'testUser91005300', 'mail': '91005300@ouyangtest.com', 'phone': '13912224213',
        #                   'passportId': 2473025, 'subSystemId': 1,
        #                   'corpInfo': {'corpName': 'corpName91005300', 'corpEngName': 'EngName91005300',
        #                                'corpShortName': 'ShortName91005300'}}
        # self.user2Info = {'userName': 'testUser91190b21', 'mail': '91190b21@ouyangtest.com', 'phone': '13905120407',
        #                   'passportId': 2473026, 'subSystemId': 1,
        #                   'corpInfo': {'corpName': 'corpName91190b21', 'corpEngName': 'EngName91190b21',
        #                                'corpShortName': 'ShortName91190b21'}}

        # product test info
        # self.user1Info = {'userName': 'testUser36df53f0', 'mail': '36df53f0@ouyangtest.com', 'phone': '13924256515',
        #                   'passportId': None,
        #                   'subSystemId': 1,
        #                   'corpInfo': {'corpName': 'corpName36df53f0', 'corpEngName': 'EngName36df53f0',
        #                                'corpShortName': 'ShortName36df53f0'}}
        # self.user2Info = {'userName': 'testUser36eff5c0', 'mail': '36eff5c0@ouyangtest.com', 'phone': '13983632431',
        #                   'passportId': None,
        #                   'subSystemId': 1,
        #                   'corpInfo': {'corpName': 'corpName36eff5c0', 'corpEngName': 'EngName36eff5c0',
        #                                'corpShortName': 'ShortName36eff5c0'}}

    def getUuid(self):
        string = str(uuid.uuid1())
        return string.replace("-", "")

    def getAppkeyList(self, data={}):
        url = self.usedIP + "/rest/v1/app/list/"

        response = requests.post(url, headers=self.header, data=json.dumps(data))
        assert_equal(response.status_code, 200)
        return json.loads(response.text)


    @parameterized.expand(input=testData.get("getAppkeyList")) # 得到这个测试用例的测试数据
    @attr(dataType="parame")
    def testGetAppkeyList(self, name, input, expect):
        url = self.usedIP + "/rest/v1/app/list/"
        response = requests.post(url, headers=self.header, data=json.dumps(input))

        result = get_unmatch_list(expect, response.text)
        if result:
            print "Failed, expect:: %s, actually:: %s" % (
                str(result).replace("u'", "'").decode("unicode_escape"), response.text)
            assert_true(False,  )
        else:
            assert_true(True)

        print "testGetAppkeyList: Passed"

    def testGetUserDetails(self):
        # 获取用户细节信息
        url = self.usedIP + "/rest/v1/user/detail/"
        data = {"passportId": self.user2Info.get("passportId"),
                "userName": self.user2Info.get("userName")}

        response = requests.get(url, headers=self.header, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0",response.text)
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_equal(jsonObj.get("result").get("userName"), self.user2Info.get("userName"))
        print "testGetUserDetails: Passed"

    def testGetUserList(self):
        # 获取多个用户信息
        url = self.usedIP + "/rest/v1/user/list"
        data = {}
        response = requests.post(url, headers=self.header, data=json.dumps(data))
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_true(len(jsonObj.get("result").get("list")) == 10)

        data = {"userName": "ouyangkui_uat"}
        response = requests.post(url, headers=self.header, data=json.dumps(data))
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_equal(len(jsonObj.get("result").get("list")), 1)

        data = {"passportIds": [self.user1Info.get("passportId"), self.user2Info.get("passportId")]}
        response = requests.post(url, headers=self.header, data=json.dumps(data))
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_equal(len(jsonObj.get("result").get("list")), 2)
        print "testGetUserList: Passed"

    def getAccountsInfo(self, passportIds):
        url = self.usedIP + "/rest/v1/user/account"
        data = {"passportIds": passportIds}
        response = requests.get(url, params=data)
        return json.loads(response.text)

    def testGetAccountsInfo(self):
        # 获取用户信息验证
        passportIds = "%s,%s" % (self.user1Info.get("passportId"), self.user2Info.get("passportId"))
        jsonObj = self.getAccountsInfo(passportIds)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_equal(len(jsonObj.get("result")), 2)
        print "testGetAccountsInfo: Passed"

    def testUserModify(self):
        # 修改用户认证状态及官方技能开发者
        url = self.usedIP + "/rest/v1/user/modify"
        data = {"passportId": self.user1Info.get("passportId"),
                "officialSkillDeveloperFlag": 1,
                "authenticateDeveloper": 1
                }
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        print "testUserModify: Passed"

    def testCheckInfoExisting(self):
        # 判断账户信息是否已存在（/rest/v1/user/isAccountExist）
        url = self.usedIP + "/rest/v1/user/isAccountExist"

        # 查用户名
        data = {"dataType": 1,
                "dataValue": self.user1Info.get("userName")}
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_true(jsonObj.get("result"))

        data = {"dataType": 1,
                "dataValue": "notExistingUserName"}
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_false(jsonObj.get("result"))

        # 查手机
        data = {"dataType": 2,
                "dataValue": self.user1Info.get("phone")}
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_true(jsonObj.get("result"))

        # 查邮箱
        data = {"dataType": 3,
                "dataValue": self.user1Info.get("mail")}
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_true(jsonObj.get("result"))

        print "testCheckInfoExisting: Passed"

    def testCheckShortNameExisting(self):
        # 判断英文简称是否已存在（/rest/v1/user/isCorpNameExist）

        url = self.usedIP + "/rest/v1/user/isCorpNameExist"
        data = {"dataType": 1,
                "dataValue": self.user1Info.get("corpInfo").get("corpEngName")}
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_true(jsonObj.get("result"))

        data = {"dataType": 2,
                "dataValue": self.user1Info.get("corpInfo").get("corpEngName")}
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_false(jsonObj.get("result"))

        print "testCheckShortNameExisting: Passed"

    def testChangeAppToUser(self):
        # APP更换用户（/rest/v1/app/change/user）
        url = self.usedIP + "/rest/v1/app/change/user"
        data = {"appKey": self.appKey,
                "passportId": self.user1Info.get("passportId")}
        response = requests.get(url=url, params=data)
        jsonObj = json.loads(response.text)
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")

        appKeyInfo = self.getAppkeyList({"appKey": self.appKey})
        assert_equal(self.user1Info.get("passportId"), appKeyInfo.get("result").get("list")[0].get("passportId"))

        print "testChangeAppToUser: Passed"

    def addEnterpriseUser(self, getUserInfo=False):
        # 注册用户，
        url = self.usedIP + "/rest/v1/user/add"
        shortUuid = self.getUuid()[0:8]
        phone = "139" + ''.join([str(random.randint(0, 8)) for _ in range(8)])
        data = {"userName": "testUser" + shortUuid,
                "phone": phone,
                "mail": shortUuid + "@ouyangtest.com",
                "corpInfo": {"corpName": "corpName" + shortUuid,
                             "corpShortName": "ShortName" + shortUuid,
                             "corpEngName": "EngName" + shortUuid,
                             },
                "subSystemId": 1
                }
        response = requests.post(url, headers=self.header, data=json.dumps(data))
        jsonObj = json.loads(response.text)
        # 判断注册成功
        assert_equal(jsonObj.get("errorCode"), "0", jsonObj)
        if getUserInfo:
            data["passportId"] = json.loads(response.text).get("result")
            return data
        else:
            return json.loads(response.text)

    def testAddEnterpriseUser(self):
        # 注册用户，并且查询该用户信息，然后验证
        jsonObj = self.addEnterpriseUser()
        assert_equal(jsonObj.get("errorCode"), "0", jsonObj)
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")

        new_passportId = jsonObj.get("result")
        jsonObj = self.getAccountsInfo(str(new_passportId))
        assert_equal(jsonObj.get("errorCode"), "0")
        assert_equal(jsonObj.get("errorMsg"), u"请求成功")
        assert_equal(len(jsonObj.get("result")), 1)

        print "testAddEnterpriseUser: Passed"
    def testlistappkey(self):
        appkeydict={"yabnwjpzklukrt63dbtg7guzwgnc2aezxd5kvsyk":["1.0.3","1.0.2"],
                    "dwrxhpglinzq7xxbz2topdqlbfkmawfr2otkbva3":["1.0.2"]
                    }
        url=self.usedIP + '/rest/v1/skill/list'
        data={
            'passportId':'1059005',
            'skillId':'a970bb564cd04ce5a4431187dc6e2fea'
        }
        response=requests.get(url,params=data)
        jsonObj=json.loads(response.text)
        print jsonObj
        print response.text
        assert_true(jsonObj.get('errorCode')=='0')

        assert_equal(jsonObj.get('errorMsg'),u'请求成功')
        for info in jsonObj.get('result').get('list'):
            print info
            key=info.get("appKey")
            print key
            assert_in(key,appkeydict.keys())
            # a=appkeydict.get(key)
            # print a
            assert_true(info.get("skillVersion") in appkeydict.get(key))
    def appkeyskillcount(self):
        #查询某用户技能关联产品数量（/rest/v1/skill/productCnt）
        url=self.usedIP + '/rest/v1/skill/productCnt'
        data={
            'passportId':'1059005',
            'skillId':'a970bb564cd04ce5a4431187dc6e2fea'
        }
        response=requests.get(url,params=data)
        print response.text
        print type(response.text)
        jsonObj=json.loads(response.text)
        print jsonObj
        print type(jsonObj)
        assert_equal(jsonObj.get('errorCode'),'0')
        assert_equal(jsonObj.get('errorMsg'),u'请求成功')
        print "pass"
    def modifyskill(self):
        #批量修改产品已关联技能的版本信息（/rest/v1/skill/updateVersion）
        url=self.usedIP +'/rest/v1/skill/updateVersion'
        formdata={
            "ids": [124316],
            "skillVersion": "1.0.1",
            "skillId": "8399084c2f474eb89b9ab26203b11a61",
            "skillName": "图片",

            "skillCode": "8399084c2f474eb89b9ab26203b11a61_1.0.2",
            "skillIcon": "http://dcs-resources-oss.hivoice.cn/skill/icon/skill_icon_default.png",
            "skillDesc": "图片",
            "sentences": ["图片"]
            }
        response=requests.post(url,headers=self.header,data=json.dumps(formdata))
        print response.text



if __name__ == '__main__':
    dm = TestdpsManage()
    # dm.testGetAppkeyList()
    # dm.testGetUserDetails()
    # dm.testGetUserList()
    # dm.testGetAccountsInfo()
    # dm.testUserModify()
    # dm.testCheckInfoExisting()
    # dm.testCheckShortNameExisting()
    # dm.testChangeAppToUser()
    # dm.testAddEnterpriseUser()
    # dm.testappkeyskill()
    # dm.testlistappkey()
    dm.appkeyskillcount()
    # dm.modifyskill()


